package rpc.remote.transport.socket;

import lombok.extern.slf4j.Slf4j;
import rpc.factory.SingletonFactory;
import rpc.remote.dto.RpcRequest;
import rpc.remote.dto.RpcResponse;
import rpc.remote.handler.RpcRequestHandler;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @ClassName: SocketRpcRequestHandlerRunnable
 * @Description:
 * @author: Kowk
 * @since:1.0.0
 */
@Slf4j
public class SocketRpcRequestHandlerRunnable implements Runnable{
    private final Socket socket;
    private final RpcRequestHandler rpcRequestHandler;

    public SocketRpcRequestHandlerRunnable(Socket socket ) {
        this.socket = socket;
        this.rpcRequestHandler = SingletonFactory.getInstance(RpcRequestHandler.class);
    }


    @Override
    public void run() {
        log.info("服务通过线程[{}]处理来自客户端的消息",Thread.currentThread().getName());
        try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())){
            RpcRequest request = (RpcRequest) objectInputStream.readObject();
            Object result = rpcRequestHandler.handle(request);
            objectOutputStream.writeObject(RpcResponse.success(result,request.getRequestId()));
            objectOutputStream.flush();
        } catch (IOException | ClassNotFoundException e) {
            log.error("服务处理客户端消息时发生异常",e);
        }
    }
}
